// 监听扩展安装或更新
chrome.runtime.onInstalled.addListener(() => {
  // 初始化存储
  chrome.storage.local.get(['stocks', 'autoRefresh', 'refreshInterval'], (result) => {
    if (!result.stocks) {
      chrome.storage.local.set({ stocks: ['sh000001', 'sz399001'] });
    }
    if (result.autoRefresh === undefined) {
      chrome.storage.local.set({ autoRefresh: true });
    }
    if (!result.refreshInterval) {
      chrome.storage.local.set({ refreshInterval: 30 });
    }
  });
});

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'refreshStocks') {
    // 触发股票数据刷新
    chrome.tabs.sendMessage(sender.tab.id, { type: 'refreshStocks' });
  }
});

// 设置定时刷新
chrome.alarms.create('refreshStocks', { periodInMinutes: 1 });

chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === 'refreshStocks') {
    chrome.storage.local.get(['autoRefresh'], (result) => {
      if (result.autoRefresh) {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
          if (tabs[0]) {
            chrome.tabs.sendMessage(tabs[0].id, { type: 'refreshStocks' });
          }
        });
      }
    });
  }
}); 